'use strict';

const Controller = require('egg').Controller;
class BorrowController extends Controller {
  // 查询全部借阅记录
  async findAllBorrow() {
    const { ctx } = this;
    const data = await ctx.service.borrowService.findAllBorrow();
    ctx.body = { code: 200, data };
  }
  // 添加借阅记录
  async addBorrow() {
    const { ctx } = this;
    if (!ctx.request.body.userName) {
      ctx.body = { code: 501, msg: '缺少必填参数,必须上传userName字段!' };
    } else if (!ctx.request.body.isbn) {
      ctx.body = { code: 501, msg: '缺少必填参数,必须上传图书isbn字段!' };
    } else {
      const data = await ctx.service.borrowService.addBorrow(ctx.request.body.userName, ctx.request.body.isbn);
      ctx.body = { data };
    }
  }
  // 根据用户名获取借阅记录，即查询该用户的借阅记录
  async selectBorrowByUserName() {
    const { ctx } = this;
    const { userName } = ctx.request.body;
    if (!userName) {
      ctx.body = { code: 501, msg: '缺少必填参数,必须上传userName字段!' };
    } else {
      const data = await ctx.service.borrowService.selectBorrowByUserName(userName);
      ctx.body = { code: 200, data };
    }
  }
  // 根据isbn查询借阅纪律，即查询该书的借阅记录
  async selectBorrowByIsbn() {
    const { ctx } = this;
    const { isbn } = ctx.request.body;
    if (!isbn) {
      ctx.body = { code: 501, msg: '缺少必填参数,必须上传isbn字段!' };
    } else {
      const data = await ctx.service.borrowService.selectBorrowByIsbn(isbn);
      ctx.body = { code: 200, data };
    }
  }
  // 删除借阅记录，必须有用户名和isbn才能删除
  async deleteBorrow() {
    const { ctx } = this;
    // const { userName } = ctx.params;
    // const { isbn } = ctx.params;
    const { userName, isbn } = ctx.query;
    if (!userName) {
      ctx.body = { code: 501, msg: '缺少必填参数,必须上传userName字段!' };
    } else if (!isbn) {
      ctx.body = { code: 501, msg: '缺少必填参数,必须上传图书isbn字段!' };
    } else {
      const data = await ctx.service.borrowService.deleteBorrow(userName, isbn);
      ctx.body = { data };
    }
  }
}
module.exports = BorrowController;
